﻿using UnityEngine;
using System.Collections;

public class SingletonMonoBehaviour<T> : MonoBehaviour where T : SingletonMonoBehaviour<T>
{
	private static T _instance;
	public static T Instance { 
		get { 
			if(_instance == null)
			{
				_instance = BuildIntance();
				DontDestroyOnLoad(_instance);
				_instance.Begin();
			}
			return _instance;	
		} 
	}

	private static T BuildIntance()
	{
		T obj = GameObject.FindObjectOfType<T>();
		if(obj) return obj;

		GameObject go = new GameObject("SingletonMonoBehaviour[" +  typeof(T).Name + "]");
		return go.AddComponent<T>();
	}

	protected virtual void Begin(){}
}
